<template>
  <div class="profile-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="primary" 
          :icon="ArrowLeft" 
          @click="handleBack"
          size="small"
          class="back-button"
        >
          返回
        </el-button>
        <div class="header-title">
          <h1>个人中心</h1>
          <p>管理个人信息和账户设置</p>
        </div>
      </div>
    </div>

    <div class="profile-layout">
      <!-- 左侧个人信息卡片 -->
      <div class="profile-sidebar">
        <el-card class="profile-card">
          <div class="avatar-container" @click="handleAvatarUpload">
            <el-avatar :size="80" :src="getAvatarUrl(userInfo.avatar)" :icon="UserFilled">
              {{ (userInfo.name || userInfo.username || '').charAt(0).toUpperCase() }}
            </el-avatar>
            <div class="avatar-overlay">
              <el-icon><Camera /></el-icon>
              <span class="upload-text">点击上传</span>
            </div>
          </div>
          <div class="profile-info">
            <h3>{{ userInfo.name || userInfo.username }}</h3>
            <p class="profile-role">{{ getRoleLabel(userInfo.roles[0]) || '-' }}</p>
            <p class="profile-department">{{ userInfo.department || '-' }}</p>
            <p class="profile-email">{{ userInfo.email }}</p>
          </div>
          <div class="profile-stats">
            <div class="stat-item">
              <span class="stat-value">{{ userStats.total_projects }}</span>
              <span class="stat-label">参与项目</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ userStats.total_tasks }}</span>
              <span class="stat-label">完成任务</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ userStats.total_hours }}</span>
              <span class="stat-label">工作时长</span>
            </div>
          </div>
        </el-card>

        <!-- 快捷操作 -->
        <el-card class="quick-actions">
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="action-buttons">
            <!-- <el-button type="primary" :icon="Edit" @click="handleEditProfile">
              编辑资料
            </el-button> -->
            <el-button type="success" :icon="Key" @click="handleChangePassword">
              修改密码
            </el-button>
            <el-button type="warning" :icon="Setting" @click="handleAccountSettings">
              账户设置
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 右侧内容区域 -->
      <div class="profile-content">
        <!-- 标签页 -->
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>基本信息</span>
                  <el-button type="primary" size="small" @click="handleEditProfile">
                    编辑
                  </el-button>
                </div>
              </template>
              
              <el-descriptions :column="2" border>
                <el-descriptions-item label="用户名">
                  <div class="info-item">
                    <el-icon><User /></el-icon>
                    <span>{{ userInfo.username }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="姓名">
                  <div class="info-item">
                    <el-icon><Avatar /></el-icon>
                    <span>{{ userInfo.name || '-' }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">
                  <div class="info-item">
                    <el-icon><Message /></el-icon>
                    <span>{{ userInfo.email }}</span>
                    <el-tag v-if="userInfo.is_verified" type="success" size="small" style="margin-left: 8px;">
                      已验证
                    </el-tag>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="手机号">
                  <div class="info-item">
                    <el-icon><Phone /></el-icon>
                    <span>{{ userInfo.phone || '-' }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="部门">
                  <div class="info-item">
                    <el-icon><OfficeBuilding /></el-icon>
                    <span>{{ userInfo.department || '-' }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="职位">
                  <div class="info-item">
                    <el-icon><Briefcase /></el-icon>
                    <span>{{ userInfo.position || '-' }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="角色">
                  <div class="info-item">
                    <el-icon><Star /></el-icon>
                    <el-tag :type="getRoleType(userInfo.roles[0] || '') as any" effect="dark">
                      {{ getRoleLabel(userInfo.roles[0]) || '-' }}
                    </el-tag>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="状态">
                  <div class="info-item">
                    <el-icon><CircleCheck v-if="userInfo.status === 'active'" /><CircleClose v-else /></el-icon>
                    <el-tag :type="userInfo.status === 'active' ? 'success' : 'danger'" effect="dark">
                      {{ userInfo.status === 'active' ? '活跃' : '禁用' }}
                    </el-tag>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="注册时间">
                  <div class="info-item">
                    <el-icon><Calendar /></el-icon>
                    <span>{{ formatDateTime(userInfo.created_at) }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="最后登录">
                  <div class="info-item">
                    <el-icon><Clock /></el-icon>
                    <span>{{ formatDateTime(userInfo.last_login) || '-' }}</span>
                    <el-tag v-if="userInfo.login_count" type="info" size="small" style="margin-left: 8px;">
                      登录{{ userInfo.login_count }}次
                    </el-tag>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="个人简介" :span="2">
                  <div class="bio-section">
                    <el-icon><Document /></el-icon>
                    <span>{{ userInfo.bio || '暂无个人简介' }}</span>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-tab-pane>

          <!-- 安全设置 -->
          <el-tab-pane label="安全设置" name="security">
            <el-card>
              <template #header>
                <span>安全设置</span>
              </template>
              
              <div class="security-settings">
                <div class="security-item">
                  <div class="security-info">
                    <h4>登录密码</h4>
                    <p>定期更换密码可以提高账户安全性</p>
                  </div>
                  <el-button type="primary" @click="handleChangePassword">
                    修改密码
                  </el-button>
                </div>
                
                <el-divider />
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>邮箱验证</h4>
                    <p>已验证的邮箱: {{ userInfo.email }}</p>
                  </div>
                  <el-tag :type="userInfo.is_verified ? 'success' : 'warning'">
                    {{ userInfo.is_verified ? '已验证' : '未验证' }}
                  </el-tag>
                </div>
                
                <el-divider />
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>手机验证</h4>
                    <p>{{ userInfo.phone ? `已绑定手机: ${userInfo.phone}` : '未绑定手机号' }}</p>
                  </div>
                  <el-button type="primary" size="small" @click="handleChangePhone">
                    {{ userInfo.phone ? '更换手机' : '绑定手机' }}
                  </el-button>
                </div>
                
                <el-divider />
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>登录日志</h4>
                    <p>查看最近的登录记录</p>
                  </div>
                  <el-button type="primary" size="small" @click="handleViewLoginLogs">
                    查看日志
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-tab-pane>

          <!-- 通知设置 -->
          <el-tab-pane label="通知设置" name="notification">
            <el-card>
              <template #header>
                <span>通知设置</span>
              </template>
              
              <el-form :model="notificationSettings" label-width="150px">
                <el-form-item label="邮件通知">
                  <div class="notification-group">
                    <el-switch v-model="notificationSettings.email_task_assigned" />
                    <span>任务分配通知</span>
                  </div>
                  <div class="notification-group">
                    <el-switch v-model="notificationSettings.email_task_completed" />
                    <span>任务完成通知</span>
                  </div>
                  <div class="notification-group">
                    <el-switch v-model="notificationSettings.email_project_update" />
                    <span>项目更新通知</span>
                  </div>
                  <div class="notification-group">
                    <el-switch v-model="notificationSettings.email_deadline_reminder" />
                    <span>截止日期提醒</span>
                  </div>
                </el-form-item>
                
                <el-form-item label="系统通知">
                  <div class="notification-group">
                    <el-switch v-model="notificationSettings.system_task_assigned" />
                    <span>任务分配通知</span>
                  </div>
                  <div class="notification-group">
                    <el-switch v-model="notificationSettings.system_task_completed" />
                    <span>任务完成通知</span>
                  </div>
                  <div class="notification-group">
                    <el-switch v-model="notificationSettings.system_project_update" />
                    <span>项目更新通知</span>
                  </div>
                  <div class="notification-group">
                    <el-switch v-model="notificationSettings.system_deadline_reminder" />
                    <span>截止日期提醒</span>
                  </div>
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleSaveNotificationSettings" :loading="saving">
                    保存设置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>

          <!-- 偏好设置 -->
          <el-tab-pane label="偏好设置" name="preferences">
            <el-card>
              <template #header>
                <span>偏好设置</span>
              </template>
              
              <el-form :model="preferences" label-width="150px">
                <el-form-item label="主题设置">
                  <div class="preference-group">
                    <el-radio-group v-model="preferences.theme" @change="handleThemeChange">
                      <el-radio label="light">浅色主题</el-radio>
                      <el-radio label="dark">深色主题</el-radio>
                      <el-radio label="auto">跟随系统</el-radio>
                    </el-radio-group>
                    <p class="preference-hint">选择您喜欢的界面主题，跟随系统将根据系统设置自动切换</p>
                  </div>
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleSavePreferences" :loading="saving">
                    保存设置
                  </el-button>
                  <el-button @click="handleResetPreferences">
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>

          <!-- 活动记录 -->
          <el-tab-pane label="活动记录" name="activity">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>活动记录</span>
                  <div style="display: flex; gap: 8px;">
                    <el-button type="primary" size="small" @click="fetchActivityLogs" :loading="loadingActivities">
                      刷新
                    </el-button>
                  </div>
                </div>
              </template>
              
              <!-- 筛选条件 -->
              <div class="activity-filters">
                <el-form :inline="true" :model="activityFilters" class="filter-form">
                  <el-form-item label="操作类型">
                    <el-select v-model="activityFilters.action" placeholder="全部" clearable style="width: 150px" @change="handleFilterChange">
                      <el-option label="全部" value="" />
                      <el-option label="创建" value="create" />
                      <el-option label="更新" value="update" />
                      <el-option label="删除" value="delete" />
                      <el-option label="查看" value="view" />
                      <el-option label="登录" value="login" />
                      <el-option label="登出" value="logout" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="目标类型">
                    <el-select v-model="activityFilters.target_type" placeholder="全部" clearable style="width: 150px" @change="handleFilterChange">
                      <el-option label="全部" value="" />
                      <el-option label="项目" value="project" />
                      <el-option label="任务" value="task" />
                      <el-option label="需求" value="requirement" />
                      <el-option label="缺陷" value="defect" />
                      <el-option label="用户" value="user" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="开始日期">
                    <el-date-picker
                      v-model="activityFilters.start_date"
                      type="date"
                      placeholder="选择开始日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 150px"
                      @change="handleFilterChange"
                    />
                  </el-form-item>
                  <el-form-item label="结束日期">
                    <el-date-picker
                      v-model="activityFilters.end_date"
                      type="date"
                      placeholder="选择结束日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 150px"
                      @change="handleFilterChange"
                    />
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="resetActivityFilters">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
              
              <!-- 活动列表 -->
              <div v-loading="loadingActivities">
                <el-timeline v-if="activityLogs && activityLogs.length > 0">
                  <el-timeline-item
                    v-for="activity in activityLogs"
                    :key="activity.id"
                    :timestamp="formatDateTime(activity.created_at)"
                    :type="getActivityType(activity.action) as any"
                  >
                    <div class="activity-content">
                      <h4>{{ getActionText(activity.action) }}</h4>
                      <p>{{ activity.description || '无描述' }}</p>
                      <div class="activity-meta">
                        <el-tag size="small" :type="getActivityType(activity.action) as any">
                          {{ getActionText(activity.action) }}
                        </el-tag>
                        <el-tag size="small" type="info" v-if="activity.target_type">
                          {{ getTargetTypeText(activity.target_type) }}
                        </el-tag>
                        <span class="activity-target" v-if="activity.target_name">
                          {{ activity.target_name }}
                        </span>
                        <span class="activity-ip" v-if="activity.ip_address">
                          IP: {{ activity.ip_address }}
                        </span>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                
                <div v-else class="empty-state">
                  <el-empty description="暂无活动记录" />
                </div>
              </div>
              
              <!-- 分页 -->
              <div class="activity-pagination" v-if="activityTotal > 0">
                <el-pagination
                  v-model:current-page="activityPage"
                  v-model:page-size="activityPageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  :total="activityTotal"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleActivityPageSizeChange"
                  @current-change="handleActivityPageChange"
                />
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog
      v-model="editProfileDialogVisible"
      title="编辑个人资料"
      width="640px"
      class="profile-edit-dialog"
      @close="handleDialogClose"
    >
      <template #header>
        <div class="dialog-header">
          <el-icon class="dialog-icon"><User /></el-icon>
          <span class="dialog-title">编辑个人资料</span>
        </div>
      </template>
      
      <div class="dialog-content">
        <el-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileFormRules"
          label-width="110px"
          class="profile-edit-form"
        >
          <div class="form-section">
            <div class="section-title">基本信息</div>
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="profileForm.username" 
                placeholder="请输入用户名"
                clearable
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input 
                v-model="profileForm.name" 
                placeholder="请输入姓名"
                clearable
              >
                <template #prefix>
                  <el-icon><Avatar /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input 
                v-model="profileForm.email" 
                placeholder="请输入邮箱"
                clearable
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input 
                v-model="profileForm.phone" 
                placeholder="请输入手机号"
                clearable
              >
                <template #prefix>
                  <el-icon><Phone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>
          
          <div class="form-section">
            <div class="section-title">工作信息</div>
            <el-form-item label="部门" prop="department">
              <el-input 
                v-model="profileForm.department" 
                placeholder="请输入部门"
                clearable
              >
                <template #prefix>
                  <el-icon><OfficeBuilding /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="职位" prop="position">
              <el-input 
                v-model="profileForm.position" 
                placeholder="请输入职位"
                clearable
              >
                <template #prefix>
                  <el-icon><Briefcase /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>
          
          <div class="form-section">
            <div class="section-title">个人简介</div>
            <el-form-item label="简介" prop="bio">
              <el-input
                v-model="profileForm.bio"
                type="textarea"
                :rows="4"
                placeholder="请输入个人简介，最多500字"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editProfileDialogVisible = false" size="large">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSaveProfile" 
            :loading="saving"
            size="large"
          >
            保存修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="changePasswordDialogVisible"
      title="修改密码"
      width="540px"
      class="password-change-dialog"
      @close="handlePasswordDialogClose"
    >
      <template #header>
        <div class="dialog-header">
          <el-icon class="dialog-icon"><Key /></el-icon>
          <span class="dialog-title">修改密码</span>
        </div>
      </template>
      
      <div class="dialog-content">
        <div class="password-tips">
          <el-alert
            title="密码安全提示"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="tips-content">
                <p>• 密码长度至少6位</p>
                <p>• 建议使用字母、数字和特殊字符的组合</p>
                <p>• 定期更换密码可以提高账户安全性</p>
              </div>
            </template>
          </el-alert>
        </div>
        
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordFormRules"
          label-width="110px"
          class="password-change-form"
        >
          <el-form-item label="当前密码" prop="current_password">
            <el-input
              v-model="passwordForm.current_password"
              type="password"
              show-password
              placeholder="请输入当前密码"
              clearable
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_password">
            <el-input
              v-model="passwordForm.new_password"
              type="password"
              show-password
              placeholder="请输入新密码（至少6位）"
              clearable
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirm_password">
            <el-input
              v-model="passwordForm.confirm_password"
              type="password"
              show-password
              placeholder="请再次输入新密码"
              clearable
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="changePasswordDialogVisible = false" size="large">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSavePassword" 
            :loading="saving"
            size="large"
          >
            确认修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 登录日志对话框 -->
    <el-dialog
      v-model="loginLogsDialogVisible"
      title="登录日志"
      width="900px"
      class="login-logs-dialog"
      @close="handleLoginLogsDialogClose"
    >
      <template #header>
        <div class="dialog-header">
          <el-icon class="dialog-icon"><Document /></el-icon>
          <span class="dialog-title">登录日志</span>
        </div>
      </template>
      
      <div class="dialog-content">
        <!-- 筛选条件 -->
        <div class="login-logs-filters">
          <el-form :inline="true" :model="loginLogsFilters" class="filter-form">
            <el-form-item label="登录状态">
              <el-select 
                v-model="loginLogsFilters.status" 
                placeholder="全部" 
                clearable 
                style="width: 120px"
                @change="handleLoginLogsFilterChange"
              >
                <el-option label="全部" value="" />
                <el-option label="成功" value="success" />
                <el-option label="失败" value="failed" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="loginLogsFilters.start_date"
                type="date"
                placeholder="选择开始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 160px"
                @change="handleLoginLogsFilterChange"
              />
            </el-form-item>
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="loginLogsFilters.end_date"
                type="date"
                placeholder="选择结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 160px"
                @change="handleLoginLogsFilterChange"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="resetLoginLogsFilters">重置</el-button>
              <el-button type="primary" @click="fetchLoginLogs" :loading="loadingLoginLogs">
                刷新
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 登录日志表格 -->
        <div v-loading="loadingLoginLogs" class="login-logs-table">
          <el-table
            :data="loginLogs"
            stripe
            style="width: 100%"
            :empty-text="'暂无登录记录'"
          >
            <el-table-column prop="login_time" label="登录时间" width="180">
              <template #default="{ row }">
                <div class="time-cell">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatDateTime(row.login_time) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="ip_address" label="IP地址" width="150">
              <template #default="{ row }">
                <div class="ip-cell">
                  <el-icon><Location /></el-icon>
                  <span>{{ row.ip_address }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="device_info" label="设备信息" min-width="200">
              <template #default="{ row }">
                <div class="device-cell">
                  <span v-if="row.device_info">{{ row.device_info }}</span>
                  <span v-else class="text-muted">未知设备</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="user_agent" label="用户代理" min-width="250" show-overflow-tooltip>
              <template #default="{ row }">
                <div class="user-agent-cell">
                  <span>{{ row.user_agent || '-' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="success" label="登录状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.success ? 'success' : 'danger'" effect="dark">
                  <el-icon v-if="row.success"><CircleCheck /></el-icon>
                  <el-icon v-else><CircleClose /></el-icon>
                  <span style="margin-left: 4px;">
                    {{ row.success ? '成功' : '失败' }}
                  </span>
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="login-logs-pagination" v-if="loginLogsTotal > 0">
          <el-pagination
            v-model:current-page="loginLogsPage"
            v-model:page-size="loginLogsPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="loginLogsTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleLoginLogsPageSizeChange"
            @current-change="handleLoginLogsPageChange"
          />
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="loginLogsDialogVisible = false" size="large">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 更换手机号对话框 -->
    <el-dialog
      v-model="changePhoneDialogVisible"
      title="更换手机号"
      width="540px"
      class="change-phone-dialog"
      @close="handlePhoneDialogClose"
    >
      <template #header>
        <div class="dialog-header">
          <el-icon class="dialog-icon"><Phone /></el-icon>
          <span class="dialog-title">{{ userInfo.phone ? '更换手机号' : '绑定手机号' }}</span>
        </div>
      </template>
      
      <div class="dialog-content">
        <div class="phone-tips" v-if="userInfo.phone">
          <el-alert
            title="当前已绑定手机号"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="tips-content">
                <p>当前手机号：<strong>{{ userInfo.phone }}</strong></p>
                <p>更换手机号后，原手机号将无法用于登录和找回密码</p>
              </div>
            </template>
          </el-alert>
        </div>
        
        <el-form
          ref="phoneFormRef"
          :model="phoneForm"
          :rules="phoneFormRules"
          label-width="110px"
          class="change-phone-form"
        >
          <el-form-item label="新手机号" prop="phone">
            <el-input
              v-model="phoneForm.phone"
              placeholder="请输入11位手机号"
              clearable
              maxlength="11"
            >
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <div class="code-input-group">
              <el-input
                v-model="phoneForm.code"
                placeholder="请输入验证码"
                clearable
                maxlength="6"
                @keyup.enter="handleSavePhone"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
              <el-button
                type="primary"
                :disabled="!canSendCode || countdown > 0"
                @click="handleSendCode"
                :loading="sendingCode"
                class="send-code-btn"
              >
                {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="changePhoneDialogVisible = false" size="large">
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSavePhone" 
            :loading="saving"
            size="large"
          >
            确认{{ userInfo.phone ? '更换' : '绑定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  UserFilled,
  Key,
  Setting,
  Camera,
  User,
  Avatar,
  Message,
  Phone,
  OfficeBuilding,
  Briefcase,
  Star,
  CircleCheck,
  CircleClose,
  Calendar,
  Clock,
  Document,
  Lock,
  Location,
  ArrowLeft
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getCurrentUserProfile,
  updateCurrentUserProfile,
  uploadUserAvatar,
  changeUserPassword,
  getNotificationSettings,
  updateNotificationSettings,
  getUserActivityLogs,
  getUserStatistics,
  getUserLoginLogs,
  getUserPreferences,
  updateUserPreferences,
  type UserProfile,
  type UpdateProfileParams,
  type ChangePasswordParams,
  type NotificationSettings,
  type ActivityLog,
  type UserStats,
  type LoginLog,
  type UserPreferences
} from '@/api/profile'
import { useThemeStore } from '@/stores/theme'
import { useRoleStore } from '@/stores'
import { getAvatarUrl as getAvatarUrlUtil } from '@/utils/avatar'

// 路由
const router = useRouter()

// 响应式数据
const saving = ref(false)
const activeTab = ref('basic')
const roleStore = useRoleStore()

// 用户信息
const userInfo = ref<UserProfile>({
  id: '',
  username: '',
  name: '',
  email: '',
  department: '',
  position: '',
  phone: '',
  avatar: '',
  bio: '',
  status: 'active',
  is_verified: false,
  roles: [],
  permissions: [],
  created_at: '',
  updated_at: '',
  last_login: '',
  login_count: 0
})

// 用户统计
const userStats = ref<UserStats>({
  total_projects: 0,
  active_projects: 0,
  completed_projects: 0,
  total_tasks: 0,
  completed_tasks: 0,
  pending_tasks: 0,
  overdue_tasks: 0,
  total_hours: 0,
  this_month_hours: 0
})

// 通知设置
const notificationSettings = reactive<NotificationSettings>({
  email_task_assigned: true,
  email_task_completed: true,
  email_project_update: false,
  email_deadline_reminder: true,
  system_task_assigned: true,
  system_task_completed: true,
  system_project_update: true,
  system_deadline_reminder: true
})

// 主题store
const themeStore = useThemeStore()

// 偏好设置
const preferences = reactive<UserPreferences>({
  theme: 'light'
})
const initialPreferences = ref<UserPreferences>({ theme: 'light' })

// 活动日志
const activityLogs = ref<ActivityLog[]>([])
const loadingActivities = ref(false)
const activityPage = ref(1)
const activityPageSize = ref(20)
const activityTotal = ref(0)
const activityFilters = reactive({
  action: '',
  target_type: '',
  start_date: '',
  end_date: ''
})

// 登录日志
const loginLogs = ref<LoginLog[]>([])
const loginLogsDialogVisible = ref(false)
const loadingLoginLogs = ref(false)
const loginLogsPage = ref(1)
const loginLogsPageSize = ref(20)
const loginLogsTotal = ref(0)
const loginLogsFilters = reactive({
  status: '',
  start_date: '',
  end_date: ''
})

// 对话框状态
const editProfileDialogVisible = ref(false)
const changePasswordDialogVisible = ref(false)
const changePhoneDialogVisible = ref(false)

// 表单引用
const profileFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const phoneFormRef = ref<FormInstance>()

// 表单数据
const profileForm = reactive<UpdateProfileParams>({
  username: '',
  name: '',
  email: '',
  phone: '',
  department: '',
  position: '',
  bio: ''
})

const passwordForm = reactive<ChangePasswordParams & { confirm_password: string }>({
  current_password: '',
  new_password: '',
  confirm_password: ''
})

const phoneForm = reactive<{
  phone: string
  code: string
}>({
  phone: '',
  code: ''
})

// 表单验证规则
const profileFormRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  department: [
    { max: 50, message: '部门名称不能超过50个字符', trigger: 'blur' }
  ],
  position: [
    { max: 50, message: '职位名称不能超过50个字符', trigger: 'blur' }
  ],
  bio: [
    { max: 500, message: '个人简介不能超过500个字符', trigger: 'blur' }
  ]
}

const passwordFormRules: FormRules = {
  current_password: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirm_password: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value !== passwordForm.new_password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const phoneFormRules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value === userInfo.value.phone) {
          callback(new Error('新手机号不能与当前手机号相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 标签页切换
const handleTabClick = (tab: any) => {
  if (tab.name === 'activity') {
    // 如果还没有加载过数据，则加载
    if (activityLogs.value.length === 0 && !loadingActivities.value) {
      fetchActivityLogs()
    }
  }
}

// 编辑资料
const handleEditProfile = () => {
  Object.assign(profileForm, {
    username: userInfo.value.username,
    name: userInfo.value.name,
    email: userInfo.value.email,
    phone: userInfo.value.phone,
    department: userInfo.value.department,
    position: userInfo.value.position,
    bio: userInfo.value.bio
  })
  editProfileDialogVisible.value = true
}

// 保存资料
const handleSaveProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    await profileFormRef.value.validate()
    saving.value = true
    
    // 调用API更新用户资料
    const updatedProfile = await updateCurrentUserProfile(profileForm)
    
    // 更新本地用户信息 - 确保所有字段都更新
    if (updatedProfile) {
      userInfo.value = {
        ...userInfo.value,
        ...updatedProfile,
        // 确保保留原有的一些字段（如 roles, permissions 等）
        roles: updatedProfile.roles || userInfo.value.roles,
        permissions: updatedProfile.permissions || userInfo.value.permissions,
        avatar: updatedProfile.avatar || userInfo.value.avatar,
        status: updatedProfile.status || userInfo.value.status,
        is_verified: updatedProfile.is_verified !== undefined ? updatedProfile.is_verified : userInfo.value.is_verified,
        created_at: updatedProfile.created_at || userInfo.value.created_at,
        updated_at: updatedProfile.updated_at || userInfo.value.updated_at,
        last_login: updatedProfile.last_login || userInfo.value.last_login,
        login_count: updatedProfile.login_count !== undefined ? updatedProfile.login_count : userInfo.value.login_count
      }
      
      // 同时更新用户 store 中的信息
      const userStore = useUserStore()
      if (userStore.userInfo) {
        userStore.updateUserInfo({
          name: updatedProfile.name,
          email: updatedProfile.email,
          phone: updatedProfile.phone,
          department: updatedProfile.department,
          position: updatedProfile.position,
          bio: updatedProfile.bio,
          avatar: updatedProfile.avatar
        })
      }
    }
    
    ElMessage.success('个人资料更新成功')
    editProfileDialogVisible.value = false
  } catch (error: any) {
    console.error('保存个人资料失败:', error)
    ElMessage.error(error?.response?.data?.message || error?.message || '保存个人资料失败')
  } finally {
    saving.value = false
  }
}

// 修改密码
const handleChangePassword = () => {
  Object.assign(passwordForm, {
    current_password: '',
    new_password: '',
    confirm_password: ''
  })
  changePasswordDialogVisible.value = true
}

// 保存密码
const handleSavePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    saving.value = true
    
    // 调用API修改密码
    await changeUserPassword({
      current_password: passwordForm.current_password,
      new_password: passwordForm.new_password
    })
    
    ElMessage.success('密码修改成功')
    changePasswordDialogVisible.value = false
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    saving.value = false
  }
}

// 查看登录日志
const handleViewLoginLogs = async () => {
  loginLogsDialogVisible.value = true
  loginLogsPage.value = 1
  resetLoginLogsFilters()
  await fetchLoginLogs()
}

// 获取登录日志
const fetchLoginLogs = async () => {
  try {
    loadingLoginLogs.value = true
    const params: any = {
      page: loginLogsPage.value,
      limit: loginLogsPageSize.value
    }
    
    if (loginLogsFilters.start_date) {
      params.start_date = loginLogsFilters.start_date
    }
    if (loginLogsFilters.end_date) {
      params.end_date = loginLogsFilters.end_date
    }
    
    const response = await getUserLoginLogs(params)
    
    if (response.data) {
      let logs = response.data.data || []
      
      // 前端筛选登录状态
      if (loginLogsFilters.status) {
        const isSuccess = loginLogsFilters.status === 'success'
        logs = logs.filter(log => log.success === isSuccess)
      }
      
      loginLogs.value = logs
      loginLogsTotal.value = response.data.total || 0
    } else {
      loginLogs.value = []
      loginLogsTotal.value = 0
    }
  } catch (error) {
    console.error('获取登录日志失败:', error)
    ElMessage.error('获取登录日志失败')
    loginLogs.value = []
    loginLogsTotal.value = 0
  } finally {
    loadingLoginLogs.value = false
  }
}

// 登录日志筛选变化
const handleLoginLogsFilterChange = () => {
  loginLogsPage.value = 1
  fetchLoginLogs()
}

// 重置登录日志筛选
const resetLoginLogsFilters = () => {
  loginLogsFilters.status = ''
  loginLogsFilters.start_date = ''
  loginLogsFilters.end_date = ''
}

// 登录日志分页大小变化
const handleLoginLogsPageSizeChange = (size: number) => {
  loginLogsPageSize.value = size
  loginLogsPage.value = 1
  fetchLoginLogs()
}

// 登录日志页码变化
const handleLoginLogsPageChange = (page: number) => {
  loginLogsPage.value = page
  fetchLoginLogs()
}

// 关闭登录日志对话框
const handleLoginLogsDialogClose = () => {
  loginLogs.value = []
  loginLogsPage.value = 1
  resetLoginLogsFilters()
}

// 更换手机号相关
const sendingCode = ref(false)
const countdown = ref(0)
let countdownTimer: NodeJS.Timeout | null = null

const canSendCode = computed(() => {
  return phoneForm.phone && /^1[3-9]\d{9}$/.test(phoneForm.phone) && phoneForm.phone !== userInfo.value.phone
})

// 打开更换手机号对话框
const handleChangePhone = () => {
  phoneForm.phone = ''
  phoneForm.code = ''
  changePhoneDialogVisible.value = true
}

// 发送验证码
const handleSendCode = async () => {
  if (!phoneFormRef.value) return
  
  try {
    // 先验证手机号格式
    await phoneFormRef.value.validateField('phone')
    
    sendingCode.value = true
    
    // TODO: 调用后端发送验证码接口
    // 这里先模拟发送，实际应该调用后端API
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('验证码已发送，请查收短信')
    
    // 开始倒计时
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        if (countdownTimer) {
          clearInterval(countdownTimer)
          countdownTimer = null
        }
      }
    }, 1000)
  } catch (error: any) {
    if (error?.fields) {
      // 验证失败
      return
    }
    console.error('发送验证码失败:', error)
    ElMessage.error(error?.response?.data?.message || error?.message || '发送验证码失败')
  } finally {
    sendingCode.value = false
  }
}

// 保存手机号
const handleSavePhone = async () => {
  if (!phoneFormRef.value) return
  
  try {
    await phoneFormRef.value.validate()
    saving.value = true
    
    // TODO: 验证验证码是否正确
    // 这里先模拟验证，实际应该调用后端API验证验证码
    // const verifyResult = await verifyPhoneCode(phoneForm.phone, phoneForm.code)
    // if (!verifyResult.success) {
    //   ElMessage.error('验证码错误或已过期')
    //   return
    // }
    
    // 更新手机号
    const updatedProfile = await updateCurrentUserProfile({
      phone: phoneForm.phone
    })
    
    if (updatedProfile) {
      userInfo.value = {
        ...userInfo.value,
        ...updatedProfile
      }
      
      // 同时更新用户 store 中的信息
      const userStore = useUserStore()
      if (userStore.userInfo) {
        userStore.updateUserInfo({
          phone: updatedProfile.phone
        })
      }
    }
    
    ElMessage.success(userInfo.value.phone ? '手机号更换成功' : '手机号绑定成功')
    changePhoneDialogVisible.value = false
  } catch (error: any) {
    console.error('保存手机号失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '保存手机号失败'
    ElMessage.error(errorMessage)
  } finally {
    saving.value = false
  }
}

// 关闭手机号对话框
const handlePhoneDialogClose = () => {
  phoneForm.phone = ''
  phoneForm.code = ''
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
  countdown.value = 0
  phoneFormRef.value?.clearValidate()
}

// 保存通知设置
const handleSaveNotificationSettings = async () => {
  try {
    saving.value = true
    const response = await updateNotificationSettings(notificationSettings)
    if (response.data) {
      Object.assign(notificationSettings, response.data)
    }
    ElMessage.success('通知设置更新成功')
  } catch (error) {
    console.error('保存通知设置失败:', error)
    ElMessage.error('保存通知设置失败')
  } finally {
    saving.value = false
  }
}

// 主题变化处理
const handleThemeChange = (theme: 'light' | 'dark' | 'auto') => {
  // 立即应用主题
  themeStore.setTheme(theme)
}

// 保存偏好设置
const handleSavePreferences = async () => {
  try {
    saving.value = true
    const response = await updateUserPreferences(preferences)
    
    // 确保正确解析响应数据（兼容不同的响应格式）
    const prefsData = response.data || response
    
    if (prefsData) {
      Object.assign(preferences, prefsData)
      initialPreferences.value = { ...preferences }
      // 同步到主题store
      if (preferences.theme) {
        themeStore.setTheme(preferences.theme as 'light' | 'dark' | 'auto')
      }
    }
    
    ElMessage.success(response.message || '偏好设置保存成功')
  } catch (error: any) {
    console.error('保存偏好设置失败:', error)
    const errorMsg = error?.response?.data?.message || error?.message || '保存偏好设置失败'
    ElMessage.error(errorMsg)
  } finally {
    saving.value = false
  }
}

// 重置偏好设置
const handleResetPreferences = () => {
  Object.assign(preferences, initialPreferences.value)
  if (preferences.theme) {
    themeStore.setTheme(preferences.theme as 'light' | 'dark' | 'auto')
  }
}

// 获取活动日志
const fetchActivityLogs = async () => {
  try {
    loadingActivities.value = true
    
    const params: any = {
      page: activityPage.value,
      limit: activityPageSize.value
    }
    
    // 添加筛选条件
    if (activityFilters.action) {
      params.action = activityFilters.action
    }
    if (activityFilters.target_type) {
      params.target_type = activityFilters.target_type
    }
    if (activityFilters.start_date) {
      params.start_date = activityFilters.start_date
    }
    if (activityFilters.end_date) {
      params.end_date = activityFilters.end_date
    }
    
    const response = await getUserActivityLogs(params)
    
    // 处理响应数据
    // response 是 ApiResponse<ActivityLogListResponse>
    // response.data 是 ActivityLogListResponse { data: ActivityLog[], total, page, limit }
    if (response && response.data) {
      const listData = response.data
      activityLogs.value = listData.data || []
      activityTotal.value = listData.total || 0
    } else {
      activityLogs.value = []
      activityTotal.value = 0
    }
  } catch (error) {
    console.error('获取活动日志失败:', error)
    activityLogs.value = []
    activityTotal.value = 0
    ElMessage.error('获取活动记录失败')
  } finally {
    loadingActivities.value = false
  }
}

// 筛选条件变化
const handleFilterChange = () => {
  activityPage.value = 1
  fetchActivityLogs()
}

// 重置筛选条件
const resetActivityFilters = () => {
  activityFilters.action = ''
  activityFilters.target_type = ''
  activityFilters.start_date = ''
  activityFilters.end_date = ''
  activityPage.value = 1
  fetchActivityLogs()
}

// 分页变化
const handleActivityPageChange = (page: number) => {
  activityPage.value = page
  fetchActivityLogs()
}

const handleActivityPageSizeChange = (size: number) => {
  activityPageSize.value = size
  activityPage.value = 1
  fetchActivityLogs()
}

// 获取目标类型文本
const getTargetTypeText = (targetType: string) => {
  const typeMap: Record<string, string> = {
    project: '项目',
    task: '任务',
    requirement: '需求',
    defect: '缺陷',
    user: '用户',
    document: '文档',
    version: '版本',
    test_case: '测试用例'
  }
  return typeMap[targetType] || targetType
}

// 对话框关闭处理
const handleDialogClose = () => {
  profileFormRef.value?.resetFields()
}

const handlePasswordDialogClose = () => {
  passwordFormRef.value?.resetFields()
}

// 辅助函数
const getRoleLabel = (role: string) => {
  return roleStore.getRoleName(role)
}

const getRoleType = (role: string) => {
  return roleStore.getRoleTagType(role)
}


const getActivityType = (action: string) => {
  const actionMap: Record<string, string> = {
    task_completed: 'success',
    task_created: 'primary',
    task_updated: 'warning',
    project_created: 'success',
    project_updated: 'warning',
    login: 'info',
    logout: 'info',
    profile_update: 'primary',
    password_change: 'warning',
    comment_add: 'primary'
  }
  return actionMap[action] || 'info'
}

const getActionText = (action: string) => {
  const actionMap: Record<string, string> = {
    task_completed: '完成任务',
    task_created: '创建任务',
    task_updated: '更新任务',
    project_created: '创建项目',
    project_updated: '更新项目',
    login: '用户登录',
    logout: '用户登出',
    profile_update: '资料更新',
    password_change: '密码修改',
    comment_add: '添加评论'
  }
  return actionMap[action] || action
}

// 日期时间格式化
const formatDateTime = (datetime: string | undefined) => {
  if (!datetime) return '-'
  
  const date = new Date(datetime)
  const now = new Date()
  const diffTime = Math.abs(now.getTime() - date.getTime())
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    // 今天
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `今天 ${hours}:${minutes}`
  } else if (diffDays === 1) {
    // 昨天
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `昨天 ${hours}:${minutes}`
  } else if (diffDays < 7) {
    // 一周内
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekday = weekdays[date.getDay()]
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    return `${weekday} ${hours}:${minutes}`
  } else {
    // 更早
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}年${month}月${day}日`
  }
}

// 格式化日期

// 头像上传
const handleAvatarUpload = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = async (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file) return
    
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      ElMessage.error('请选择图片文件')
      return
    }
    
    // 验证文件大小（5MB）
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过5MB')
      return
    }
    
    try {
      saving.value = true
      const response = await uploadUserAvatar(file)
      
      // 获取完整的头像URL
      const avatarUrl = response.data?.avatar || ''
      
      // 更新本地用户信息
      if (avatarUrl) {
        // 保存原始URL（相对路径），getAvatarUrl函数会处理URL拼接
        userInfo.value.avatar = avatarUrl
        
        // 同时更新用户 store 中的头像
        const userStore = useUserStore()
        if (userStore.userInfo) {
          userStore.updateUserInfo({
            avatar: avatarUrl
          })
        }
      }
      
      ElMessage.success('头像上传成功')
    } catch (error: any) {
      console.error('头像上传失败:', error)
      const errorMessage = error?.response?.data?.message || error?.message || '头像上传失败'
      ElMessage.error(errorMessage)
    } finally {
      saving.value = false
    }
  }
  input.click()
}

// 获取头像URL（使用工具函数）
const getAvatarUrl = (avatar: string | undefined): string => {
  return getAvatarUrlUtil(avatar)
}

// 账户设置
const handleAccountSettings = () => {
  activeTab.value = 'security'
}

// 初始化数据
const initializeData = async () => {
  try {
    // 获取用户资料
    userInfo.value = await getCurrentUserProfile()
    console.log('用户资料数据:', userInfo.value)
    console.log('最后登录时间:', userInfo.value?.last_login)
    
    // 获取用户统计
    const statsResponse = await getUserStatistics()
    if (statsResponse.data) {
      userStats.value = statsResponse.data
    }
    
    // 获取通知设置
    const notificationResponse = await getNotificationSettings()
    if (notificationResponse.data) {
      Object.assign(notificationSettings, notificationResponse.data)
    }
    
    // 获取用户偏好设置
    try {
      const preferencesResponse = await getUserPreferences()
      
      // 确保正确解析响应数据（兼容不同的响应格式）
      const prefsData = preferencesResponse.data || preferencesResponse
      
      if (prefsData) {
        // 更新偏好设置
        if (prefsData.theme) {
          preferences.theme = prefsData.theme
          // 同步到主题store
          themeStore.setTheme(prefsData.theme as 'light' | 'dark' | 'auto')
        }
        if (prefsData.language) {
          preferences.language = prefsData.language
        }
        if (prefsData.timezone) {
          preferences.timezone = prefsData.timezone
        }
        initialPreferences.value = { ...preferences }
      }
    } catch (error) {
      // 如果接口不存在，从localStorage读取
      const savedTheme = localStorage.getItem('theme') as 'light' | 'dark' | 'auto' | null
      if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
        preferences.theme = savedTheme
        themeStore.setTheme(savedTheme)
      } else {
        // 使用主题store的当前值
        preferences.theme = themeStore.themeMode
      }
      initialPreferences.value = { ...preferences }
    }
    
    // 获取活动日志
    await fetchActivityLogs()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 初始化
onMounted(() => {
  // 静默加载角色数据，失败不影响页面显示
  roleStore.fetchRoles().catch(error => {
    // 如果是权限错误，静默处理，不显示错误消息
    if (error && typeof error === 'object' && 'isPermissionError' in error && error.isPermissionError()) {
      console.warn('当前用户无权限访问角色列表，将使用默认角色标签')
    } else {
      console.error('加载角色数据失败:', error)
    }
  })
  initializeData()
})
</script>

<style scoped>
.profile-container {
  padding: 20px 24px;
  background: var(--bg-secondary);
  min-height: calc(100vh - 60px);
  height: fit-content;
  transition: background-color 0.3s ease, color 0.3s ease;
  color: var(--text-primary);
}

/* 浅色主题下的渐变背景 */
.theme-light .profile-container {
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
}

/* 深色主题下的背景 */
.theme-dark .profile-container {
  background: var(--bg-secondary);
}

.page-header {
  margin-bottom: 20px;
  padding: 10px 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: center;
}

.back-button {
  flex-shrink: 0;
}

.header-title {
  text-align: center;
}

.header-title h1 {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
  transition: color 0.3s ease;
}

.header-title p {
  color: var(--text-secondary);
  margin: 0;
  font-size: 14px;
  font-weight: 400;
  transition: color 0.3s ease;
}

.profile-layout {
  display: flex;
  gap: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.profile-sidebar {
  width: 320px;
  flex-shrink: 0;
}

.profile-card {
  margin-bottom: 16px;
  text-align: center;
  background: var(--bg-card);
  border-radius: 16px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-color-light);
  transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease, border-color 0.3s ease;
  padding: 24px 20px;
  color: var(--text-primary);
}

.profile-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12);
}

.avatar-container {
  position: relative;
  display: inline-block;
  cursor: pointer;
  margin-bottom: 20px;
  transition: transform 0.3s ease;
}

.avatar-container:hover {
  transform: scale(1.05);
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(52, 152, 219, 0.85), rgba(41, 128, 185, 0.85));
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  font-size: 24px;
  backdrop-filter: blur(2px);
  gap: 4px;
}

.avatar-overlay .upload-text {
  font-size: 12px;
  font-weight: 500;
  margin-top: 2px;
}

.profile-info {
  text-align: center;
  margin-bottom: 20px;
  padding: 0 8px;
}

.profile-info h3 {
  font-size: 22px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px 0;
  line-height: 1.3;
  transition: color 0.3s ease;
}

.profile-role {
  color: var(--color-primary);
  font-weight: 600;
  margin: 0 0 6px 0;
  font-size: 13px;
  text-transform: uppercase;
  letter-spacing: 0.8px;
  transition: color 0.3s ease;
}

.profile-department {
  color: var(--text-secondary);
  margin: 0 0 6px 0;
  font-size: 14px;
  line-height: 1.4;
  transition: color 0.3s ease;
}

.profile-email {
  color: var(--text-tertiary);
  font-size: 13px;
  margin: 0;
  font-weight: 500;
  word-break: break-all;
  transition: color 0.3s ease;
}

.profile-stats {
  display: flex;
  justify-content: space-around;
  padding-top: 18px;
  border-top: 2px solid #f3f4f6;
  margin-top: 18px;
  gap: 12px;
}

.stat-item {
  text-align: center;
  position: relative;
  flex: 1;
  padding: 0 6px;
}

.stat-item:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 1px;
  height: 28px;
  background: linear-gradient(to bottom, transparent, rgba(52, 152, 219, 0.3), transparent);
}

.stat-value {
  display: block;
  font-size: 24px;
  font-weight: 700;
  color: #3b82f6;
  margin-bottom: 4px;
  line-height: 1.2;
}

.stat-label {
  font-size: 11px;
  color: #9ca3af;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.8px;
  line-height: 1.3;
}

.quick-actions {
  margin-bottom: 0;
  background: var(--bg-card);
  border-radius: 16px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-color-light);
  transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease, border-color 0.3s ease;
  padding: 16px;
  color: var(--text-primary);
}

.quick-actions:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12);
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.action-buttons .el-button {
  justify-content: flex-start;
  border-radius: 10px;
  padding: 12px 16px;
  font-weight: 500;
  font-size: 14px;
  transition: all 0.3s ease;
  border: 1px solid #e5e7eb;
  background: #ffffff;
  color: #475569;
  height: auto;
}

.action-buttons .el-button:hover {
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: transparent;
}

.action-buttons .el-button--success {
  background: linear-gradient(135deg, #f0fdf4, #dcfce7);
  color: #059669;
  border-color: #bbf7d0;
}

.action-buttons .el-button--success:hover {
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
}

.action-buttons .el-button--warning {
  background: linear-gradient(135deg, #fffbeb, #fef3c7);
  color: #d97706;
  border-color: #fde68a;
}

.action-buttons .el-button--warning:hover {
  background: linear-gradient(135deg, #f59e0b, #d97706);
  color: white;
}

.profile-content {
  flex: 1;
  min-width: 0;
}

.profile-content .el-card {
  background: var(--bg-card);
  border-radius: 16px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-color-light);
  transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease, border-color 0.3s ease;
  padding: 20px;
  color: var(--text-primary);
}

.profile-content .el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 16px 0;
  margin-bottom: 16px;
  border-bottom: 2px solid #f3f4f6;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  letter-spacing: -0.3px;
  transition: color 0.3s ease;
}

.security-settings {
  max-width: 700px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 16px;
  transition: background-color 0.3s ease;
  border-radius: 10px;
  margin: 0 -8px;
  padding-left: 16px;
  padding-right: 16px;
}

.security-item:hover {
  background-color: rgba(59, 130, 246, 0.05);
}

.security-info {
  flex: 1;
  margin-right: 16px;
}

.security-info h4 {
  margin: 0 0 6px 0;
  color: var(--text-primary);
  font-size: 16px;
  font-weight: 600;
  transition: color 0.3s ease;
}

.security-info p {
  margin: 0;
  color: var(--text-secondary);
  font-size: 13px;
  line-height: 1.5;
  transition: color 0.3s ease;
}

.notification-group {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 14px;
  padding: 14px 16px;
  border-left: 3px solid #3498db;
  background: #f8fafc;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.notification-group:hover {
  background: rgba(52, 152, 219, 0.08);
  transform: translateX(4px);
}

.notification-group span {
  font-weight: 500;
  color: var(--text-primary);
  font-size: 14px;
  transition: color 0.3s ease;
}

.preference-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 14px;
  padding: 16px;
  border-left: 3px solid #3498db;
  background: #f8fafc;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.preference-group:hover {
  background: rgba(52, 152, 219, 0.08);
  transform: translateX(4px);
}

.preference-hint {
  margin: 0;
  color: #6b7280;
  font-size: 13px;
  line-height: 1.5;
  margin-top: 8px;
}

.activity-content {
  padding: 6px 0;
}

.activity-content h4 {
  margin: 0 0 8px 0;
  color: var(--text-primary);
  font-size: 16px;
  font-weight: 600;
  transition: color 0.3s ease;
}

.activity-content p {
  margin: 0 0 10px 0;
  color: var(--text-secondary);
  line-height: 1.5;
  font-size: 13px;
  transition: color 0.3s ease;
}

.activity-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
  margin-top: 8px;
}

.activity-target {
  font-size: 12px;
  color: var(--text-secondary);
  background: var(--bg-tertiary);
  padding: 4px 10px;
  border-radius: 12px;
  transition: background-color 0.3s ease, color 0.3s ease;
}

.activity-ip {
  font-size: 12px;
  color: var(--text-tertiary);
  font-family: monospace;
  transition: color 0.3s ease;
}

.activity-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  background: var(--bg-tertiary);
  border-radius: 12px;
  margin: 16px 0;
  transition: background-color 0.3s ease;
}

.empty-state p {
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 500;
  transition: color 0.3s ease;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.info-item .el-icon {
  color: #9ca3af;
  font-size: 16px;
}

.bio-section {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
  line-height: 1.6;
}

.bio-section .el-icon {
  color: #9ca3af;
  margin-top: 2px;
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 20px 16px;
    background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
  }
  
  .profile-layout {
    flex-direction: column;
    gap: 20px;
  }
  
  .profile-sidebar {
    width: 100%;
  }
  
  .profile-stats {
    flex-direction: row;
    gap: 12px;
  }
  
  .stat-item:not(:last-child)::after {
    display: none;
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    text-align: left;
  }
  
  .security-info {
    margin-right: 0;
  }
  
  .notification-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .action-buttons .el-button {
    width: 100%;
    justify-content: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    text-align: left;
    align-items: flex-start;
  }
  
  .profile-content .el-card {
    padding: 20px;
  }
}

/* 标签页样式优化 */
:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__nav-wrap) {
  border-radius: 10px;
  background: #f8fafc;
  padding: 4px;
}

:deep(.el-tabs__nav) {
  border: none !important;
}

:deep(.el-tabs__item) {
  color: #6b7280;
  font-weight: 500;
  padding: 0 20px;
  height: 40px;
  line-height: 40px !important;
  border-radius: 8px;
  transition: all 0.3s ease;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  vertical-align: middle;
  box-sizing: border-box;
  text-align: center;
}

:deep(.el-tabs__item:hover) {
  color: #374151;
  background: rgba(59, 130, 246, 0.1);
}

:deep(.el-tabs__item.is-active) {
  color: white;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  border-radius: 10px;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  display: none;
}

/* 确保标签页文字完全居中 */
:deep(.el-tabs__item .el-tabs__item__content) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

/* 按钮样式优化 */
:deep(.el-button--primary) {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  border: none;
  color: white;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.25);
  border-radius: 10px;
  padding: 10px 20px;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(59, 130, 246, 0.4);
}

:deep(.el-button--small) {
  padding: 8px 16px;
  font-size: 14px;
}

/* 描述列表样式优化 */
:deep(.el-descriptions) {
  margin-top: 4px;
}

:deep(.el-descriptions__table) {
  border-collapse: separate;
  border-spacing: 0 10px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #374151;
  background: #f8fafc;
  border-radius: 6px;
  padding: 10px 14px;
  width: 140px;
  border: 1px solid #e5e7eb;
  font-size: 14px;
}

:deep(.el-descriptions__content) {
  color: #6b7280;
  font-weight: 500;
  padding: 10px 14px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
  font-size: 14px;
}

:deep(.el-descriptions__cell) {
  padding-bottom: 0;
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 20px;
  font-weight: 500;
  padding: 6px 14px;
  border: none;
  font-size: 13px;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, #ef4444, #dc2626);
  color: white;
}

:deep(.el-tag--warning) {
  background: linear-gradient(135deg, #f59e0b, #d97706);
  color: white;
}

:deep(.el-tag--info) {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  color: white;
}

/* 分割线样式优化 */
:deep(.el-divider) {
  margin: 18px 0;
  border-color: #e5e7eb;
}

/* 表单样式优化 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
  padding-bottom: 8px;
}

/* 开关样式优化 */
:deep(.el-switch) {
  --el-switch-on-color: #10b981;
}

/* 时间线样式优化 */
:deep(.el-timeline-item__timestamp) {
  color: #9ca3af;
  font-size: 13px;
  font-weight: 500;
}

:deep(.el-timeline-item__node) {
  width: 12px;
  height: 12px;
  border-width: 3px;
}

/* 对话框样式优化 */
:deep(.profile-edit-dialog),
:deep(.password-change-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.profile-edit-dialog .el-dialog__header),
:deep(.password-change-dialog .el-dialog__header) {
  padding: 24px 28px 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  border-bottom: 1px solid #e5e7eb;
  margin: 0;
}

:deep(.profile-edit-dialog .el-dialog__body),
:deep(.password-change-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.profile-edit-dialog .el-dialog__footer),
:deep(.password-change-dialog .el-dialog__footer) {
  padding: 20px 28px 24px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
  margin: 0;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.dialog-icon {
  font-size: 24px;
  color: #3b82f6;
}

.dialog-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  letter-spacing: -0.3px;
}

.dialog-content {
  padding: 28px;
  max-height: 70vh;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单样式优化 */
.profile-edit-form,
.password-change-form {
  margin-top: 8px;
}

.form-section {
  margin-bottom: 28px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f3f4f6;
  position: relative;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  bottom: -2px;
  width: 60px;
  height: 2px;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  border-radius: 2px;
}

:deep(.profile-edit-form .el-form-item),
:deep(.password-change-form .el-form-item) {
  margin-bottom: 22px;
}

:deep(.profile-edit-form .el-form-item__label),
:deep(.password-change-form .el-form-item__label) {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
  padding-bottom: 10px;
}

:deep(.profile-edit-form .el-input__wrapper),
:deep(.password-change-form .el-input__wrapper) {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.profile-edit-form .el-input__wrapper:hover),
:deep(.password-change-form .el-input__wrapper:hover) {
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.15);
}

:deep(.profile-edit-form .el-input.is-focus .el-input__wrapper),
:deep(.password-change-form .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

:deep(.profile-edit-form .el-textarea__inner),
:deep(.password-change-form .el-textarea__inner) {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  padding: 12px 14px;
  font-size: 14px;
  line-height: 1.6;
}

:deep(.profile-edit-form .el-textarea__inner:hover),
:deep(.password-change-form .el-textarea__inner:hover) {
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.15);
}

:deep(.profile-edit-form .el-textarea.is-focus .el-textarea__inner),
:deep(.password-change-form .el-textarea.is-focus .el-textarea__inner) {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

:deep(.profile-edit-form .el-input__prefix),
:deep(.password-change-form .el-input__prefix) {
  color: #9ca3af;
  left: 12px;
}

:deep(.profile-edit-form .el-input__inner),
:deep(.password-change-form .el-input__inner) {
  padding-left: 38px;
  font-size: 14px;
}

/* 密码修改对话框特殊样式 */
.password-tips {
  margin-bottom: 24px;
}

.tips-content {
  font-size: 13px;
  line-height: 1.8;
}

/* 登录日志对话框样式 */
:deep(.login-logs-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.login-logs-dialog .el-dialog__header) {
  padding: 24px 28px 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  border-bottom: 1px solid #e5e7eb;
  margin: 0;
}

:deep(.login-logs-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.login-logs-dialog .el-dialog__footer) {
  padding: 20px 28px 24px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
  margin: 0;
}

.login-logs-filters {
  padding: 20px 28px;
  background: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
}

.login-logs-filters .filter-form {
  margin: 0;
}

.login-logs-table {
  padding: 20px 28px;
  min-height: 300px;
}

.login-logs-table .time-cell,
.login-logs-table .ip-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.login-logs-table .time-cell .el-icon,
.login-logs-table .ip-cell .el-icon {
  color: #6b7280;
  font-size: 16px;
}

.login-logs-table .device-cell {
  color: #374151;
  font-size: 14px;
}

.login-logs-table .device-cell .text-muted {
  color: #9ca3af;
  font-style: italic;
}

.login-logs-table .user-agent-cell {
  color: #6b7280;
  font-size: 13px;
  font-family: 'Courier New', monospace;
}

.login-logs-pagination {
  padding: 20px 28px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  background: #f8fafc;
}

/* 更换手机号对话框样式 */
:deep(.change-phone-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.change-phone-dialog .el-dialog__header) {
  padding: 24px 28px 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
  border-bottom: 1px solid #e5e7eb;
  margin: 0;
}

:deep(.change-phone-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.change-phone-dialog .el-dialog__footer) {
  padding: 20px 28px 24px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
  margin: 0;
}

.phone-tips {
  margin-bottom: 24px;
}

.change-phone-form {
  margin-top: 8px;
}

.code-input-group {
  display: flex;
  gap: 12px;
  width: 100%;
}

.code-input-group .el-input {
  flex: 1;
}

.send-code-btn {
  white-space: nowrap;
  min-width: 120px;
}

.tips-content p {
  margin: 4px 0;
}

:deep(.password-change-dialog .el-alert) {
  border-radius: 10px;
  border: 1px solid #e0e7ff;
  background: linear-gradient(135deg, #eff6ff 0%, #f0f9ff 100%);
}

:deep(.password-change-dialog .el-alert__icon) {
  color: #3b82f6;
  font-size: 18px;
}

:deep(.password-change-dialog .el-alert__title) {
  font-weight: 600;
  color: #1e40af;
  font-size: 14px;
  margin-bottom: 8px;
}

/* 对话框按钮样式 */
.dialog-footer .el-button {
  min-width: 100px;
  border-radius: 10px;
  font-weight: 500;
  padding: 12px 24px;
}

.dialog-footer .el-button--primary {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  border: none;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.dialog-footer .el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(59, 130, 246, 0.4);
}

.dialog-footer .el-button:not(.el-button--primary) {
  border: 1px solid #e5e7eb;
  background: #ffffff;
  color: #6b7280;
}

.dialog-footer .el-button:not(.el-button--primary):hover {
  border-color: #d1d5db;
  background: #f9fafb;
  color: #374151;
}

/* 响应式优化 */
@media (max-width: 768px) {
  :deep(.profile-edit-dialog),
  :deep(.password-change-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  .dialog-content {
    padding: 20px;
  }
  
  :deep(.profile-edit-form .el-form-item),
  :deep(.password-change-form .el-form-item) {
    margin-bottom: 18px;
  }
  
  .form-section {
    margin-bottom: 24px;
  }
}
</style>